<?php
/**
 * 二维码类
 * User: Yan
 * Date: 2018/7/23
 * Time: 下午 10:47
 */

namespace YanQR;

# 引入phpqrcode入口文件
include APP_PATH . '/lib/phpqrcode/qrlib.php';

class QRCode
{
    private $content;
    private $errorLevel = 'L';
    private $size       = '8';
    private $fileName   = false;
    private $margin     = 1;
    private $fileSize;

    public function setContent($text = '')
    {
        $this->content = $text;
    }

    public function setErrorLevel($level = 'L')
    {
        $this->errorLevel = $level;
    }

    public function setSize($size)
    {
        $this->size = $size;
    }

    public function setSaveFileName($fileName)
    {
        $this->fileName = $fileName;
    }

    public function setMargin($margin)
    {
        $this->margin = $margin;
    }

    public function setSaveSize($size)
    {
        $this->fileSize = $size;
    }

    public function make()
    {
        if (empty($this->content)) {
            echo '内容不可为空';
            die;
        }

        \QRcode::png($this->content, $this->fileName, $this->errorLevel, $this->size, $this->margin);

        if (isset($this->fileName)) {
            # 有设置尺寸 则重新生成
            if (isset($this->fileSize)) {
                # 原图片
                $im         = imagecreatefrompng($this->fileName);
                $pic_height = imagesy($im);
                $pic_width  = imagesx($im);

                $newim = imagecreatetruecolor($this->fileSize, $this->fileSize);
                imagecopyresampled($newim, $im, 0, 0, 0, 0, $this->fileSize, $this->fileSize, $pic_width, $pic_height);
                imagepng($newim, $this->fileName);
            }
            return $this->fileName;
        }
    }

    public function getPng($path)
    {
        $im = imagecreatefrompng($path);
        return $im;
    }

    public function printPng($path)
    {
        if (empty($path)) return false;

        header("Content-type: image/png");
        $im = imagecreatefrompng($path);
        imagepng($im);
        imagedestroy($im);
    }
}